﻿using UnityEngine;  
using System.Collections;
using System;  

namespace tools{
public class MyConverter  {

	public byte[] value = null;

	public MyConverter(byte[] bytes){
		value = bytes;
	}

	public short toInt8(){

		return short.Parse(copyByte (1)[0].ToString());
	}

	public short toInt16(){
		byte[] temp = copyByte (2);
		if( BitConverter.IsLittleEndian ){
			Array.Reverse(temp);
		}
		return BitConverter.ToInt16(temp,0);
	}

	public bool toBoolean(){
		if( BitConverter.IsLittleEndian ){
			//Array.Reverse(value);
		}
		return BitConverter.ToBoolean(value,0);
	}

	public int toInt32(){
		byte[] temp = copyByte (4);
		if( BitConverter.IsLittleEndian ){
			Array.Reverse(temp);
		}
		return BitConverter.ToInt32(temp,0);
	}

	public long toInt64(){
		byte[] temp = copyByte (8);
		if( BitConverter.IsLittleEndian ){
			Array.Reverse(temp);
		}
		
		return BitConverter.ToInt64(temp,0);
	}

	public float toFloat()
	{
		int bits=toInt32();
		int s=((bits>>31)== 0)?1:-1;
		int e=((bits>>23)&0xff);
		int m=(e==0)?(bits & 0x7fffff)<<1:(bits&0x7fffff)|0x800000;
		return (float)(s*m*Math.Pow((float)2,e-150));
	}
	
	public double toDouble()
	{
		long bits=toInt64();
		int s=((bits>>63)==0)?1:-1;
		int e=(int)((bits>>52)&0x7ffL);
		long m=(e==0)?(bits&0xfffffffffffffL)<<1:(bits&0xfffffffffffffL)|0x10000000000000L;
		return (double)(s*m*Math.Pow((float)2,e-1075));
	}
	
	public string toString(){

		byte[] temp = copyByte (4);
		MyConverter conver = new MyConverter (temp);
		int length = conver.toInt32 ();
				
		if(length < 1){
			return "Error";
		}
		temp = copyByte (length);
		return System.Text.Encoding.UTF8.GetString ( temp );
	}

	
		public byte[] copyByte(int length){
		
		byte[] byteArr = new byte[length];
		Array.Copy (value,0,byteArr,0,length);
		
		if(value.Length <= length){
			value = new byte[0];
			return byteArr;
		}
		
		byte[] newSource = new byte[value.Length-length];
		Array.Copy (value,length,newSource,0,newSource.Length);
		value = newSource;
		
		return byteArr;
	}

	public byte[] copyTempByte(int length){
		byte[] byteArr = new byte[length];
		Array.Copy (value,0,byteArr,0,length);
		return byteArr;
	}
}
}
